package com.demo.app.controller;

import com.demo.app.entity.AjaxResponse;
import com.demo.app.enums.CustomExceptionType;
import com.demo.app.exception.CustomException;
import com.demo.app.service.JwtAuthService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author wangzhuangzhuang
 * @DESC: 开发登录接口（获取Token的接口）
 * "/authentication"接口用于登录验证，并且生成JWT返回给客户端
 * "/refreshtoken"接口用于刷新JWT，更新JWT令牌的有效期
 * @date 2022-02-15 15:06
 */
@RestController
public class JwtAuthController {

	@Resource
	private JwtAuthService jwtAuthService;

	@PostMapping(value = "/authentication")
	public AjaxResponse login(@RequestBody Map<String, String> map) {
		String username = map.get("username");
		String password = map.get("password");
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			return AjaxResponse.error(
					new CustomException(
							CustomExceptionType.USER_INPUT_ERROR,"用户名密码不能为空"));
		}
		try{
			return AjaxResponse.success(jwtAuthService.login(username, password));
		}catch(CustomException e){
			return AjaxResponse.error(e);
		}
	}

	@PostMapping(value = "/refreshtoken")
	public AjaxResponse refresh(@RequestHeader("${jwt.header}") String token) {
		return AjaxResponse.success(jwtAuthService.refreshToken(token));
	}

}